
var questionFormValidator;

$(document).ready(function () {
    $.validator.setDefaults({
        errorClass: "uk-text-danger",
        errorPlacement: function (error, element) {
            error.insertAfter(element.parent("div"));
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass("uk-form-danger");
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass("uk-form-danger");
        }
    });

    $("#btn_submit").click(function () {
        if ($('#description').length < 1 || $('#subject').length < 1) {
            UIkit.notify("无效的问题。", {status: "warning"});
            return;
        }
        UIkit.modal.confirm("确定提交问题？", onQuestionSubmit);
    });
    questionFormValidator = $("#form_question_info").validate({
        rules: {
            'subject:string': {
                required: true,
                maxlength: 10
            },
            'description:string': {
                required: true,
                maxlength: 200
            }
        },
        messages: {
            'subject:string': {
                required: '必填',
                maxlength: '问题类型最多 10 个字符'
            },
            'description:string': {
                required: '必填',
                maxlength: '问题的详细内容最多 200 个字符'
            }
        }
    });
});

function objectToString(o, defaultVal) {
    if (defaultVal == null)
        defaultVal = "";
    return o == null ? defaultVal : o.toString();
}

var blockingModal;
function onQuestionSubmit() {
    // var subject = $('#subject')[0].value;
    // var description = $('#description')[0].value;
    // var newAccount = { subject: subject , description:description};
    var form = $('#form_question_info');
    data = {subject:$('#subject')[0].value,description :$('#description')[0].value};
    if (data.subject == null && data.description == null) {
        UIkit.modal.alert("至少指定一个条件");
        return;
    }
    blockingModal = UIkit.modal.blockUI("正在提交...");
    $.ajax({
        url: '/api/student/add_question',
        data: JSON.stringify(data),
        method: 'POST',
        contentType: 'application/json'
    })
        .done(function () {
            blockingModal.hide();
            UIkit.modal.blockUI("提交成功！3 秒后将刷新页面。");
            setTimeout(function (args) { window.location.reload(true) }, 3000);
        })
        .fail(function (jqXHR) {
            try {
                var response = JSON.parse(jqXHR.responseText);
                if (response != null && response.error != null) {
                    UIkit.modal.alert("Error: " + response.error.message);
                } else {
                    UIkit.modal.alert("Error occurred.")
                }
            } catch (e) {
                UIkit.modal.alert("Error occurred.");
                console.error(e);
            } finally {
                blockingModal.hide();
            }
        })
}